﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using EPiAbstractions.Opinionated;
using EPiMVC.Controllers;
using EPiMVC.Templates.Web.PageTypes;
using EPiMVC.Templates.Web.ViewModels;
using EPiServer.Core;

namespace EPiMVC.Templates.Web.Controllers
{
    public class GlobalMenuController : EPiServerControllerBase<PageData>
    {
        private IPageRepository dataFactory;
        private StartPage startPage;

        public GlobalMenuController(IPageRepository dataFactory, 
            StartPage startPage)
        {
            this.dataFactory = dataFactory;
            this.startPage = startPage;
        }

        public ViewResult Index()
        {
            IEnumerable<PageData> pagesToShowInMenu = GetPagesToShowInMenu();
            
            Structure<MenuItem> menuItems = new Structure<MenuItem>();

            PageData selected = GetSelectedPage(pagesToShowInMenu);

            foreach (PageData child in pagesToShowInMenu)
            {
                MenuItem menuItem = new MenuItem(child.PageName, child.LinkURL);

                if(selected != null && child.PageLink == selected.PageLink)
                    menuItem.Selected = true;

                menuItems.AddNode(menuItem);
            }

            return View(menuItems);
        }

        private PageData GetSelectedPage(IEnumerable<PageData> pagesToShowInMenu)
        {
            PageData pageInSelectedHiearchy = CurrentPage;

            while (pageInSelectedHiearchy.PageLink != startPage.PageLink)
            {
                PageData selected = pagesToShowInMenu.FirstOrDefault(page => page.PageLink == pageInSelectedHiearchy.PageLink);
                if (selected != null)
                    return selected;

                pageInSelectedHiearchy = dataFactory.GetPage(pageInSelectedHiearchy.ParentLink);
            }

            return null;
        }

        private IEnumerable<PageData> GetPagesToShowInMenu()
        {
            IEnumerable<PageData> childrenOfStartpage = dataFactory.GetChildrenAccessibleToHttpUser<PageData>(startPage.PageLink);
            IEnumerable<PageData> pagesToShowInMenu = childrenOfStartpage.Where(page => page.VisibleInMenu);
            return pagesToShowInMenu;
        }
    }
}
